<template>
  <div class="hello">
    <!--开启摄像头的弹窗-->
    <!-- <div class="info2" @click="onTake">
      <el-image :src="url" style="width: 100%; height: 100%"></el-image>
    </div>-->
    <el-row>
      <el-col :span="12">
        <div class="box">
          <video
            id="videoCamera"
            class="canvas"
            :width="videoWidth"
            :height="videoHeight"
            autoplay
            v-show="isPic == false"
          ></video>
          <!--图片蒙层-->
          <img
            class="canvas"
            :width="videoWidth"
            :height="videoHeight"
            src="https://img-blog.csdnimg.cn/20210126152753150.png"
            style="z-index: 999;position: absolute;"
          />
          <canvas
            id="canvasCamera"
            class="canvas"
            :width="videoWidth"
            :height="videoHeight"
            v-show="isPic == true"
          >
            <img id="uploadPic" :src="url" />
          </canvas>
        </div>
      </el-col>
      <el-col :span="12">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <!-- <el-table-column prop="date" label="日期" width="180"></el-table-column> -->
          <el-table-column prop="id" label="遗传病ID" width="180"></el-table-column>
          <el-table-column label="遗传病名称" width="180">
            <template #default="scope">{{ scope.row.diease || scope.row.disease_en }}</template>
          </el-table-column>
          <el-table-column prop="probility" label="诊断概率"></el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div slot="footer">
      <cuttingdialog :url="url" v-show="ifUpload" v-on:urlchange="updateUrl"></cuttingdialog>
      <el-cascader
        :show-all-levels="false"
        @change="casChange"
        :props="props"
        clearable
        style="margin-right:50px;"
      ></el-cascader>
      <el-button @click="drawImage" icon="el-icon-camera" size="small">拍照</el-button>

      <!-- <el-button v-if="os" @click="getCompetence" icon="el-icon-video-camera" size="small">打开摄像头</el-button>
      <el-button v-else @click="stopNavigator" icon="el-icon-switch-button" size="small">关闭摄像头</el-button>-->
      <el-button @click="resetCanvas" icon="el-icon-refresh" size="small">重置</el-button>
      <el-upload
        action="#"
        :http-request="requestUpload"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="succesUpload"
        style="display: inline-block;margin-left: 10px;"
      >
        <el-button @click="uploadCanvas" icon="el-icon-upload2" size="small">上传</el-button>
      </el-upload>
      <el-button @click="submit" icon="el-icon-search" size="small" style="margin-left: 10px;">完成</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { checkbeforepersonalphoto } from '../api/api'
import cuttingdialog from "./CuttingDialog.vue"
// import { VueCropper } from "vue-cropper";
// import store from "@/store";
const careurl = '';
export default {
  name: "IvView",
  components: { cuttingdialog },
  props: {
    msg: String
  },
  data() {
    return {
      //选择的症状
      selectSyms: [],
      props: {
        multiple: true,
        lazy: true,
        emitPath: false,
        lazyLoad(node, resolve) {
          const { level } = node;
          if (level === 0) {
            let tarr = [];
            axios.get(careurl+'/category').then(res => {
              console.log(res)
              let cate = res.data.category;

              cate.forEach(function (ele, index) {
                let obj = {};
                obj.label = ele;
                obj.value = index;
                obj.leaf = level >= 1;
                tarr.push(obj)
              })
              resolve(tarr)
            })

          } else if (level === 1) {
            let tarr = [];
            axios.get(careurl+'?category=' + node.label).then(res => {
              //console.log(res.data)
              let arr = res.data.symptom;

              arr.forEach(function (ele) {
                let obj = {};
                obj.label = ele.symptom;
                obj.value = ele.symptom;
                obj.leaf = level >= 1 ? 'true' : 'false';
                tarr.push(obj)
              })
              resolve(tarr);
            })

          }else{
            resolve([])
          }

        }
      },
      // uploadDialogVisible: false,
      // // 是否显示cropper
      // visibleCropper: false,
      // options: {
      //   img: store.getters.avatar, //裁剪图片的地址
      //   autoCrop: true, // 是否默认生成截图框
      //   autoCropWidth: 200, // 默认生成截图框宽度
      //   autoCropHeight: 200, // 默认生成截图框高度
      //   fixedBox: true // 固定截图框大小 不允许改变
      // },
      // previews: {},
      windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
      windowHeight: document.documentElement.clientHeight,   //实时屏幕高度
      url: "", // 上传的图片的地址
      visible: false, //弹窗
      videoWidth: 1000, // 绘画布的宽高
      videoHeight: 800,
      os: false, //控制摄像头开关
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      imgSrc: undefined,
      imgFile: null,
      isPic: false,
      isUploadPic: false,
      tableData: [],
      loading: false,
      ifUpload: false,
    };
  },
  created() {
    console.log(this.windowHeight)
    this.videoWidth = this.windowWidth / 2 - 100;
    this.videoHeight = this.videoWidth * 0.8;
    this.onTake();

  },
  methods: {
    casSearch(node, key) {
      console.log(node, key)
    },
    casChange(e) {
      console.log(e)
      this.selectSyms = e;
    },
    submit() {
      var that = this;
      //this.imgSrc = this.imgSrc.replace(/^data:image\/\w+;base64,/, "");
      this.loading = true;
      console.log('this.imgSrc', this.imgSrc);
      let baseImg = this.imgSrc
      // baseImg = baseImg.replace(/\+/g, "%2B");
      // baseImg = baseImg.replace(/\=/g, "&3D");
      axios.defaults.timeout = 30000;
      //   console.log(encodeURI(baseImg))
      axios({
        method: 'post',
        url: careurl+'/cn_photo',
        headers: {
          "id": '1'
        },
        data: {
          photo: baseImg,
          selectSyms:this.selectSyms
        }
      }).then((response) => {          //这里使用了ES6的语法
        console.log(response)       //请求成功返回的数据
        this.tableData = response.data.all_mess;
        that.loading = false;
      }).catch(e => {
        console.log(e)
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file);
        //开始转
        reader.onload = function () {
          fileResult = reader.result;
        };
        //转 失败
        reader.onerror = function (error) {
          reject(error);
        };
        //转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },

    /*调用摄像头拍照开始*/
    onTake() {
      this.visible = true;

      this.getCompetence();
    },

    /*关闭弹窗，以及关闭摄像头功能*/
    onCancel1() {
      this.visible = false;
      this.stopNavigator(); // 关闭摄像头
    },

    // 调用摄像头权限
    getCompetence() {
      //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
      this.$nextTick(() => {
        const _this = this;
        this.os = false; //切换成关闭摄像头
        // 获取画布节点
        this.thisCancas = document.getElementById("canvasCamera");
        // 为画布指定绘画为2d类型
        this.thisContext = this.thisCancas.getContext("2d");
        //获取video节点
        this.thisVideo = document.getElementById("videoCamera");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.menavigatordiaDevices = {};
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)"
          }
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              console.log('e', e);
              _this.thisVideo.play();
            };
          })
          .catch(err => {
            console.log(err)
            this.$notify({
              title: "警告",
              message: "没有开启摄像头权限或浏览器版本不兼容.",
              type: "warning"
            });
          });
      });
    },

    //调用摄像头 --- 进行绘制图片
    drawImage() {
      // 点击，canvas画图
      console.log('this.thisVideo', this.thisVideo);
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接
      this.imgSrc = this.thisCancas.toDataURL();
      this.isPic = true;
      console.log('this.imgSrc', this.thisCancas);

      /*const imgSrc=this.imgSrc;*/
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
      console.log('resetComplete');
    },

    //重置画布
    resetCanvas() {
      // this.imgSrc = "";
      this.isPic = false;
      this.ifUpload = false;
      this.tableData = [];
      this.clearCanvas("canvasCamera");
    },
    //
    uploadCanvas() {

    },
    //
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        this.clearCanvas("canvasCamera");
        const reader = new FileReader();
        reader.readAsDataURL(file);
        let img = document.getElementById("uploadPic");
        console.log('reader', reader, img);
        reader.onload = () => {
          this.url = reader.result;
          console.log('this.url', this.url);
        };
        setTimeout(() => {
          this.thisContext.drawImage(
            img,
            0,
            0,
            this.videoWidth,
            this.videoHeight
          );
          // 获取图片base64链接
          this.imgSrc = this.thisCancas.toDataURL();
          this.isPic = true;
          console.log('this.imgSrc', this.thisCancas);
        }, 1000);
        this.ifUpload = true;
      }
    },
    //
    updateUrl(data) {
      this.url = data;
      let img = document.getElementById("uploadPic");
      setTimeout(() => {
        this.thisContext.drawImage(
          img,
          0,
          0,
          this.videoWidth,
          this.videoHeight
        );
        // 获取图片base64链接
        this.imgSrc = this.thisCancas.toDataURL();
        this.isPic = true;
        console.log('this.imgSrc', this.thisCancas);
      }, 100);
    },
    //
    succesUpload(response, file) {
      console.log('response', response);
      console.log('file', file);
    },
    //
    requestUpload() {

    },

    //关闭摄像头
    stopNavigator() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
        this.isPic = false;
      }
    },
    /*调用摄像头拍照结束*/

    /*完成拍照并对其照片进行上传*/
    onCancel() {
      this.visible = false;
      /* this.resetCanvas();*/
      // console.log(this.imgSrc);
      this.imgFile = this.dataURLtoFile(this.imgSrc, new Date() + ".png");
      console.log(this.imgFile);
      this.stopNavigator();
      // let par = {
      //   photo: this.imgFile,
      // };
      let data = new FormData();
      data.append("photo", this.imgFile); //1是图片，2是视频
      // data.append("code", this.addForm.code);
      // console.log(data);
      // checkbeforepersonalphoto上传图片的接口
      checkbeforepersonalphoto(data).then(res => {
        if (res.code == "1") {
          this.$message({
            message: "上传成功",
            type: "success"
          });
          this.url = res.data;
          // console.log('url', this.url);
        }
      });
    },

    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }
  }
};
</script>

<style scoped>
.info2 {
  width: 10%;
  height: 100px;
}
.box {
  display: flex;
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
